package com.forum.ajax.homepage;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.forum.domain.Remind;
import com.forum.domain.RemindDAO;
import com.forum.domain.Reply;
import com.forum.domain.ReplyDAO;
import com.forum.domain.Topic;
import com.forum.domain.TopicDAO;
import com.forum.domain.User;
import com.forum.domain.UserDAO;

public class SetReply extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public SetReply() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html ; charset = utf-8");
		PrintWriter out = response.getWriter();

		String text = request.getParameter("reply");
		String remindid = request.getParameter("remindid");
		String type = request.getParameter("type");
		if (type.equals("delete")) {
			deleteRemind(Integer.parseInt(remindid));
			out.print("delete success");
			return;
		} else if (type.equals("reply")) {
			String result = "";

			UserDAO ud = new UserDAO();
			RemindDAO rmd = new RemindDAO();
			ReplyDAO rd = new ReplyDAO();

			Remind remind = rmd.findById(Integer.parseInt(remindid));
			Topic topic = remind.getTopic();
			System.out.println(topic.getTitle());
			User user = remind.getUserByUserId();

			List<String> users = getAtUsers(text);
			for (int i = 0; i < users.size(); i++) {
				User ru = (User) ud.findByNickname(users.get(i)).get(0);
				if (ru == null || user == ru)
					result = result + users.get(i) + " not find ";
				else {
					Reply reply = new Reply(user, topic, ru, new Timestamp(
							System.currentTimeMillis()), text);
					rd.save(reply);
					Remind newremind = new Remind(user, topic, reply, ru);
					rmd.save(newremind);
				}
			}
			rd.getSession().beginTransaction().commit();
			rmd.getSession().beginTransaction().commit();
			deleteRemind(Integer.parseInt(remindid));
			if (result.equals(""))
				out.print("success");
			else
				out.print(result);
			return;
		}
			
			

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	private List<String> getAtUsers(String text) {
		List<String> users = new LinkedList();

		while (text.contains("@")) {
			int from = text.indexOf("@");
			int end = text.indexOf(" ", from);
			String name = text.substring(from + 1, end);
			text = text.substring(end + 1);
			users.add(name);
		}
		return users;
	}

	private void deleteRemind(Integer id) {
		RemindDAO rd = new RemindDAO();
		Remind remind = rd.findById(id);
		rd.delete(remind);
		rd.getSession().beginTransaction().commit();
	}

}
